/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.github.pig.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.common.util.TreeUtil;
import com.github.pig.admin.mapper.SysGroupMapper;
import com.github.pig.admin.mapper.SysRoleMapper;
import com.github.pig.admin.model.dto.DeptTree;
import com.github.pig.admin.model.dto.GroupTree;
import com.github.pig.admin.model.entity.SysDept;
import com.github.pig.admin.model.entity.SysGroup;
import com.github.pig.admin.model.entity.SysRole;
import com.github.pig.admin.service.SysGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysGroupServiceImpl extends ServiceImpl<SysGroupMapper, SysGroup> implements SysGroupService {
    @Autowired
    private SysGroupMapper sysGroupMapper;

    /**
     * 查询分组树
     *
     * @param sysGroupEntityWrapper
     * @return 树
     */
    @Override
    public List<GroupTree> selectListTree(EntityWrapper<SysGroup> sysGroupEntityWrapper) {
        return getGroupTree(this.selectList(sysGroupEntityWrapper), 0);
    }

    /**
     * 构建分组树
     *
     * @param groups 分组
     * @param root  根节点
     * @return
     */
    private List<GroupTree> getGroupTree(List<SysGroup> groups, int root) {
        List<GroupTree> trees = new ArrayList<>();
        GroupTree node;
        for (SysGroup group : groups) {
            if (group.getParentId().equals(group.getId())) {
                continue;
            }
            node = new GroupTree();
            node.setId(group.getId());
            node.setParentId(group.getParentId());
            node.setName(group.getName());
            node.setLabel(group.getName());
            node.setValue(group.getId());
            trees.add(node);
        }
        return TreeUtil.bulidByGroup(trees, root);
    }
}
